package com.jiantong.web.open.app.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.jiantong.user.dto.StaffManagerDto;
import com.jiantong.user.model.AppUserRole;
import com.jiantong.user.model.OrganizationUser;
import com.jiantong.user.model.User;
import com.jiantong.user.model.UserProfile;
import com.jiantong.user.service.*;
import com.jiantong.web.core.enums.ExceptionCode;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import io.terminus.common.utils.JsonMapper;
import io.terminus.pampas.openplatform.annotations.OpenBean;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by niufei on 2017/4/21.
 * 员工管理
 */
@Slf4j
@OpenBean
public class StaffManagementApis {

    private static final ObjectMapper objectMapper = JsonMapper.nonEmptyMapper().getMapper();

    @RpcConsumer
    private StaffWriteService staffWriteService;

    @RpcConsumer
    private OrganizationUserReadService organizationUserReadService;

    @RpcConsumer
    private UserReadService<User> userReadService;

    @RpcConsumer
    private AppUserRoleReadService appUserRoleReadService;

    @RpcConsumer
    private UserProfileReadService userProfileReadService;

    @RpcConsumer
    private DepartmentUserReadService departmentUserReadService;

    @RpcConsumer
    private GovernmentUserDutyReadService governmentUserDutyReadService;

//    @OpenMethod(
//            key = "create.gov.staff",
//            paramNames = {"userName","mobile","departments","declareStations","butcherFactories","role"},
//            httpMethods = RequestMethod.POST
//    )
//    public Boolean createGOVStaff(String userName , String mobile ,
//                                  List<Map<String , Object>> departments ,
//                                  List<Map<String , Object>> declareStations ,
//                                  List<Map<String , Object>> butcherFactories ,
//                                  Map<String ,String> roles) throws IOException {
//        Response<Boolean> response =
//                staffWriteService.createGOVStaff(userName,mobile,departments,declareStations,butcherFactories,
//                        objectMapper.readValue(roles.get("roles"), new TypeReference<Map<String , Object>>() {}));
//        if(!response.isSuccess()){
//            log.error("failed to create gov staff ,case={}",response.getError());
//            throw new OPServerException(response.getError());
//        }
//        return response.getResult();
//    }
//
//    @OpenMethod(
//            key = "update.gov.staff",
//            paramNames = {"userId","userName","departments","declareStations","butcherFactories","role"},
//            httpMethods = RequestMethod.PUT
//    )
//    public Boolean updateGOVStaff(Long userId ,String userName ,
//                                  List<Map<String , Object>> departments ,
//                                  List<Map<String , Object>> declareStations ,
//                                  List<Map<String , Object>> butcherFactories ,
//                                  Map<String ,String> roles) throws IOException {
//        Response<Boolean> response =
//                staffWriteService.updateGOVStaff(userId,userName,departments,declareStations,butcherFactories,
//                        objectMapper.readValue(roles.get("roles"), new TypeReference<Map<String , Object>>() {}));
//        if(!response.isSuccess()){
//            log.error("failed to update gov staff ,case={}",response.getError());
//            throw new OPServerException(response.getError());
//        }
//        return response.getResult();
//    }

    @OpenMethod(
            key = "create.ngo.staff",
            paramNames = {"staffManagerDto"},
            httpMethods = RequestMethod.POST
    )
    public Boolean createFarmStaff(StaffManagerDto staffManagerDto) {

        if(staffManagerDto == null){
            log.error("staffManagerDto should be not null");
            throw new OPClientException(ExceptionCode.OBJECT_NOT_EXIST.value(),"staffManagerDto should be not null");
        }
        String userName = staffManagerDto.getRealName();
        String mobile = staffManagerDto.getMobile();
        Integer appRole = staffManagerDto.getAppRole();
        if(Strings.isNullOrEmpty(userName) || Strings.isNullOrEmpty(mobile) || appRole == null){
            log.error("mobile 、 appRole and userName should be not null");
            throw new OPClientException(ExceptionCode.PARAMETER_NOT_EXIST.value(),"mobile 、 appRole and userName should be not null");
        }
        Response<Boolean> response = staffWriteService.createNGOStaff(userName,mobile, appRole);
        if(!response.isSuccess()){
            log.error("failed to create ngo staff ,case={}",response.getError());
            throw new OPServerException(response.getError());
        }
        return response.getResult();
    }

    @OpenMethod(
            key = "update.ngo.staff",
            paramNames = {"staffManagerDto"},
            httpMethods = RequestMethod.PUT
    )
    public Boolean updateFarmStaff(StaffManagerDto staffManagerDto){
        if(staffManagerDto == null){
            log.error("staffManagerDto should be not null");
            throw new OPClientException(ExceptionCode.OBJECT_NOT_EXIST.value(),"staffManagerDto should be not null");
        }
        String userName = staffManagerDto.getRealName();
        Integer appRole = staffManagerDto.getAppRole();
        Long userId = staffManagerDto.getUserId();
        Integer status = staffManagerDto.getStatus();
        if(userId == null || appRole == null || Strings.isNullOrEmpty(userName) || status == null){
            log.error("status、userId 、 appRole and userName should be not null");
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),"status 、userId 、 appRole and userName should be not null");
        }
        Response<Boolean> response =
                staffWriteService.updateNGOStaff(userId,userName,appRole,status);
        if(!response.isSuccess()){
            log.error("failed to update ngo staff ,case={}",response.getError());
            throw new OPServerException(response.getError());
        }
        return response.getResult();
    }

    @OpenMethod(
            key = "paging.fb.staff",
            paramNames = {"pageNo","pageSize"},
            httpMethods = RequestMethod.GET
    )
    public Paging<StaffManagerDto> pagingFBStaff(Integer pageNo , Integer pageSize){
        Response<Paging<OrganizationUser>> orgResponse = organizationUserReadService.pagingFBStaff(pageNo,pageSize);
        if(!orgResponse.isSuccess()){
            log.error("failed to paging FB staff ,case={}",orgResponse.getError());
            throw new OPServerException(orgResponse.getError());
        }
        StaffManagerDto staffManagerDto = null;
        List<StaffManagerDto> list = new ArrayList<>();
        Paging<OrganizationUser> organizationUserPaging = orgResponse.getResult();
        List<OrganizationUser> organizationUserList = organizationUserPaging.getData();
        for(OrganizationUser organizationUser : organizationUserList){
            Long userId = organizationUser.getUserId();
            Response<User> userResponse = userReadService.findById(userId);
            Response<UserProfile> userProfileResponse = userProfileReadService.findUserProfileById(userId);
            Response<AppUserRole> appUserRoleResponse = appUserRoleReadService.findByUserId(userId);
            if(!userResponse.isSuccess() || !userProfileResponse.isSuccess() || !appUserRoleResponse.isSuccess()){
                log.error("failed to find user ,case={}",userResponse.getError());
                throw new OPServerException(userResponse.getError());
            }
            if(!appUserRoleResponse.getResult().getAppRole().equals(1)){
                staffManagerDto = new StaffManagerDto();
                staffManagerDto.setUserId(userId);
                staffManagerDto.setAppRole(appUserRoleResponse.getResult().getAppRole());
                staffManagerDto.setFactoryId(organizationUser.getOrganizationId());
                staffManagerDto.setFactoryName(organizationUser.getOrganizationName());
                staffManagerDto.setMobile(userResponse.getResult().getMobile());
                staffManagerDto.setRealName(userProfileResponse.getResult().getRealName());
                staffManagerDto.setStatus(userResponse.getResult().getStatus());
                list.add(staffManagerDto);
            }
        }
        Paging<StaffManagerDto> paging = new Paging<>();
        paging.setData(list);
        paging.setTotal((long)list.size());
        return paging;
    }

    @OpenMethod(
            key = "find.fb.staff",
            paramNames = {"userId"},
            httpMethods = RequestMethod.GET
    )
    public StaffManagerDto findFBStaff(Long userId){
        Response<User> userResponse = userReadService.findById(userId);
        Response<AppUserRole> appUserRoleResponse = appUserRoleReadService.findByUserId(userId);
        Response<UserProfile> userProfileResponse = userProfileReadService.findUserProfileById(userId);
        Response<OrganizationUser> organizationUserResponse = organizationUserReadService.findOrganizationUserByUserId(userId);
        if(!userResponse.isSuccess() || !userProfileResponse.isSuccess() || !organizationUserResponse.isSuccess() || !appUserRoleResponse.isSuccess()){
            log.error("failed to find user ,case={}",userResponse.getError());
            throw new OPServerException(userResponse.getError());
        }
        StaffManagerDto staffManagerDto = new StaffManagerDto();
        staffManagerDto.setUserId(userId);
        staffManagerDto.setMobile(userResponse.getResult().getMobile());
        staffManagerDto.setStatus(userResponse.getResult().getStatus());
        staffManagerDto.setRealName(userProfileResponse.getResult().getRealName());
        staffManagerDto.setAppRole(appUserRoleResponse.getResult().getAppRole());
        staffManagerDto.setFactoryId(organizationUserResponse.getResult().getOrganizationId());
        staffManagerDto.setFactoryName(organizationUserResponse.getResult().getOrganizationName());

        return staffManagerDto;
    }

//    @OpenMethod(
//            key = "paging.gov.staff",
//            paramNames = {"pageNo","pageSize"},
//            httpMethods = RequestMethod.GET
//    )
//    public Paging<StaffManagerDto> pagingGOVStaff(Integer pageNo , Integer pageSize){
//        Response<Paging<OrganizationUser>> orgResponse = organizationUserReadService.pagingGOVStaff(pageNo,pageSize);
//        if(!orgResponse.isSuccess()){
//            log.error("failed to paging GOV staff ,case={}",orgResponse.getError());
//            throw new OPServerException(orgResponse.getError());
//        }
//        StaffManagerDto staffManagerDto = null;
//        List<StaffManagerDto> list = new ArrayList<>();
//        Paging<OrganizationUser> organizationUserPaging = orgResponse.getResult();
//        List<OrganizationUser> organizationUserList = organizationUserPaging.getData();
//        for(OrganizationUser organizationUser : organizationUserList) {
//            Long userId = organizationUser.getUserId();
//            Response<User> userResponse = userReadService.findById(userId);
//            Response<UserProfile> userProfileResponse = userProfileReadService.findUserProfileById(userId);
//            Response<DepartmentUser> departmentUserResponse = departmentUserReadService.findDepartmentUserByUserId(userId);
//            if (!userResponse.isSuccess() || !userProfileResponse.isSuccess() || !departmentUserResponse.isSuccess()) {
//                log.error("failed to find user ,case={}", userResponse.getError());
//                throw new OPServerException(userResponse.getError());
//            }
//            staffManagerDto = new StaffManagerDto();
//            staffManagerDto.setUserId(userResponse.getResult().getId());
//            staffManagerDto.setMobile(userResponse.getResult().getMobile());
//            staffManagerDto.setStatus(userResponse.getResult().getStatus());
//            staffManagerDto.setRealName(userProfileResponse.getResult().getRealName());
//            staffManagerDto.setDepartmentId(departmentUserResponse.getResult().getDepartmentId());
//            staffManagerDto.setDepartmentName(departmentUserResponse.getResult().getDepartmentName());
//            list.add(staffManagerDto);
//        }
//        Paging<StaffManagerDto> paging = new Paging<>();
//        paging.setData(list);
//        paging.setTotal(organizationUserPaging.getTotal());
//
//        return paging;
//    }

//    @OpenMethod(
//            key = "find.gov.staff",
//            paramNames = {"userId"},
//            httpMethods = RequestMethod.GET
//    )
//    public StaffManagerDto findGOVStaff(Long userId){
//        Response<User> userResponse = userReadService.findById(userId);
//        Response<UserProfile> userProfileResponse = userProfileReadService.findUserProfileById(userId);
//        Response<DepartmentUser> departmentUserResponse = departmentUserReadService.findDepartmentUserByUserId(userId);
//
//
//        if(!userResponse.isSuccess() || !userProfileResponse.isSuccess() || !departmentUserResponse.isSuccess()){
//            log.error("failed to find user ,case={}",userResponse.getError());
//            throw new OPServerException(userResponse.getError());
//        }
//
//
//        StaffManagerDto staffManagerDto = new StaffManagerDto();
//        staffManagerDto.setUserId(userId);
//        staffManagerDto.setMobile(userResponse.getResult().getMobile());
//        staffManagerDto.setRoles(userResponse.getResult().getRoles());
//        staffManagerDto.setRealName(userProfileResponse.getResult().getRealName());
//        staffManagerDto.setStatus(userResponse.getResult().getStatus());
//        staffManagerDto.setDepartmentId(departmentUserResponse.getResult().getDepartmentId());
//        staffManagerDto.setDepartmentName(departmentUserResponse.getResult().getDepartmentName());
//
//        if(departmentUserResponse.getResult().getDepartmentType() != 3 && departmentUserResponse.getResult().getDepartmentType() != 4){
//            Response<List<GovernmentUserDuty>> listResponse = governmentUserDutyReadService.findGovernmentUserDutiesByUserId(userId);
//            if(!listResponse.isSuccess()){
//                log.error("failed to find user ,case={}",userResponse.getError());
//                throw new OPServerException(userResponse.getError());
//            }
//            staffManagerDto.setGovernmentUserDutyList(listResponse.getResult());
//        }
//        return staffManagerDto;
//    }
}
